package com.app.jpa.management.producto.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.app.entity.Marca;
import com.app.jpa.management.producto.MarcaService;

@Service("jpaMarcaService")
@Repository
@Transactional
public class MarcaServiceImpl implements MarcaService {

	@PersistenceContext
	private EntityManager em;

	@Transactional(readOnly = true)
	@Override
	public List<Marca> getListMarcas() {
		List<Marca> marca = em.createNamedQuery("Marcas.getListMarcas",
				Marca.class).getResultList();
		return marca;
	}

	@Transactional(readOnly = true)
	@Override
	public Marca searchMarca(int id) {

		try {
			TypedQuery<Marca> query = em.createNamedQuery("Marcas.searchMarca",
					Marca.class);
			query.setParameter("id", id);
			Marca marca = query.getSingleResult();
			return marca;
		} catch (Exception e) {
			return null;
		}

	}

	@Transactional(readOnly = true)
	@Override
	public void saveMarca(Marca marca) {
		if (marca.getId() == null) {
			em.persist(marca);
		} else {
			em.merge(marca);
		}
		// return marca;

	}

	@Transactional(readOnly = true)
	@Override
	public void deleteMarca(Marca marca) {
		Marca m = em.merge(marca);
		em.remove(m);

	}

	@Override
	public List<Marca> searchMarcaByName(String name) {
		

		
		try {
			TypedQuery<Marca> query = em.createNamedQuery("Marcas.searchMarcaByName",
					Marca.class);
			query.setParameter("descripcion", name);
			List<Marca> marca = query.getResultList();
			return marca;
		} catch (Exception e) {
			return null;
		}
	}

}
